<template>
    <div class="content">
        <el-dialog :visible.sync="bindCard.dialogFormVisible" title="绑定卡片" size="small" :before-close="handleClose">
            <div v-loading = "upLoading">
                <el-form ref="ruleForm" :model="ruleForm" label-width="100px" :rules="rules">      
                    <el-row :gutter="21">
                        <el-col :span="12">
                            <el-form-item v-if="schoolType === '0'" label="年级" prop="sGrade">
                                <el-select v-model="ruleForm.sGrade" placeholder="请选择添加的年级" style="width:100%;" @change="queryAllClass( ruleForm.sGrade )">
                                    <el-option v-for="item in gradeList" :key="item.grade" :label="item.gradeName" :value="item.grade">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="班级" prop="sClass">
                                <el-select v-model="ruleForm.sClass" placeholder="请选择添加的班级" style="width:100%;" @change = 'vertifyName'>
                                    <el-option v-for="item in classList" :key="item.classId" :label="item.classNickName" :value="item.classId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41">
                        <el-col>
                            <el-form-item label="学生姓名" prop="sStudentName">
                                <studentName v-model="ruleForm.sStudentName" @change="queryAllName" :sClass="ruleForm.sClass"></studentName>
                                <!--<el-autocomplete v-model="ruleForm.sStudentName" :fetch-suggestions="remoteMethods" :trigger-on-focus="true" placeholder="请输入关键词" @select="queryAllName(ruleForm.sStudentName)" style="width:100%"></el-autocomplete>-->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row :gutter="41">
                        <el-col :span="23">
                            <el-form-item label="卡片类型" prop="sCardType">
                                <el-radio-group v-model="ruleForm.sCardType" @change="changeType">
                                    <el-radio label="0">IC卡</el-radio>
                                    <el-radio label="1">ID卡</el-radio>
                                    <el-radio label="2">双频卡</el-radio>
                                    <el-radio label="3">虚拟卡</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="41" v-if="ruleForm.sCardType != '3'">
                        <el-col>
                            
                            <el-form-item label="卡号" prop="cardNum">
                                <el-popover placement="top-start" trigger="focus" content="请输入卡号">
                                    <el-input slot="reference" :maxlength="10" v-model="ruleForm.cardNum" placeholder="请输入卡号"></el-input>
                                </el-popover>
                                <div class="tip">若卡面卡号以 0 开头，输入卡号时，去除前面所有的0再输入；例如：卡面卡号为【0053228075】，应输入【53228075】。</div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="41" v-else>
                        <el-col>
                            <div>
                                <div class="vertifyTip" v-if="schoolType === '0' && (ruleForm.sGrade == ''|| ruleForm.sClass == '' || ruleForm.userId == '')">请先选择年级、班级，并填写学生姓名</div>
                                <div class="vertifyTip" v-if="schoolType === '1' && (ruleForm.sClass == '' || ruleForm.userId == '')">请先选择班级，并填写学生姓名</div>
                                <el-form-item label="卡号" prop="verNum">
                                    <el-input :disabled = "true" :maxlength="10" v-model="ruleForm.verNum" placeholder="虚拟卡的卡号是系统自动生成，无需填写"></el-input>
                                    <div class="tip">虚拟卡的卡号是系统自动生成，无需填写。</div>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="持卡人关系" prop="sRelationType">
                                <el-radio-group v-model="ruleForm.sRelationType">
                                    <el-radio label="0">学生本人</el-radio>
                                    <el-radio label="1" v-if = "ruleForm.sCardType != '3'">家长</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if = "ruleForm.sRelationType === '1'"> 
                            <el-form-item label-width="0px" >
                                <el-select v-model="ruleForm.sRelation" placeholder="请选择关系" style="width:100%;">
                                    <el-option v-for="item in relationList" :key="item.pId" :label="item.sName" :value="item.pId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <footer>
                    <el-button @click="cancel">取消</el-button>
                    <el-button @click="add('ruleForm')" type="primary">确认</el-button>
                </footer>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getGrade } from 'api/classAll';
import { getClass, listSysDictByType, insertCard, getVirtualCard } from 'api/cardManagement';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from './school';
import studentName from './studentName';
import { mapGetters } from 'vuex';
export default {
    name: 'addClassSchool',
    components: { province, city, region, school, studentName },
    props: {
        bindCard: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            upLoading: false,
            gradeList: [],
            classList: [],
            schoolList: [],
            relationList: [],
            autoFill: false,
            ruleForm: {
                provinceId: '',
                cityId: '',
                areaId: '',
                schoolName: '',
                schoolId: '',
                newSchoolId: '',
                sGrade: '',
                sClass: '',
                sStudentName: '',
                userId: '',
                cardNum: '',
                verNum: '',
                sCardType: '',
                sRelationType: '',
                sRelation: ''
            },
            loading: false,
        
        // 是否培训和普通学校  1 0
            // schoolType: '0',
        // rulesSelet: {
        //   validator: (rule, value, callback) => {
        //     if (!this.provinceId && !value) {
        //       callback(new Error("请选择"));
        //     } else {
        //       callback();
        //     }
        //   },
        //   trigger: "change"
        //   // required: true, message: "请选择", trigger: "change"
        // },
        // rulesSeletcity: {
        //   validator: (rule, value, callback) => {
        //     if (!this.ruleForm.cityId && !value) {
        //       callback(new Error("请选择"));
        //     } else {
        //       callback();
        //     }
        //   },
        //   trigger: "change"
        // },
            rulesSeletarea: {
                validator: (rule, value, callback) => {
                    if (!this.ruleForm.areaId && !value) {
                        callback(new Error('请选择'));
                    } else {
                        callback();
                    }
                },
                trigger: 'change'
            },
            rules: {
                provinceId: [
                { required: true, message: '请选择', trigger: 'change' }
                ],
                cityId: [
                { required: true, message: '请选择', trigger: 'change' }
                ],
                areaId: [
                { required: true, message: '请选择', trigger: 'change' }
                ],
                schoolName: [
                { required: true, message: '请输入学校名称', trigger: 'blur' }
                ],
                sGrade: [
                { required: true, message: '请输入年级', trigger: 'change' }
                ],
                sClass: [
                { required: true, message: '请输入班级', trigger: 'change' }
                ],
                sStudentName: [
                { required: true, message: '请输入学生姓名', trigger: 'blur' }
                ],
                cardNum: [
                { required: true, message: '请输入卡号', trigger: 'blur,change' },
                { pattern: /^[1-9]\d{0,20}$/, message: '请输入正确的卡号', trigger: 'change' }
                ],
                verNum: [
                    { required: true, message: '该用户已有虚拟卡', trigger: 'blur' }
                ],
                sCardType: [{ required: true, message: '请选择卡类型', trigger: 'change' }],
                sRelationType: [{ required: true, message: '请选择持卡人关系', trigger: 'change' }]
            }
        // name: { required: true, message: "请输入学校名称", trigger: "blur" },
        // cardNum: [
        //   { message: "请输入卡号", required: true },
        //   {
        //     message: "每次最多添加10个班",
        //     trigger: "blur",
        //     pattern: /^([1-9]|10)$/
        //   }
        // ]
        };
    },
    computed: {
        ...mapGetters([
            'schoolId',
            'schoolType',
            'schoolName'
        ])
    },
    created() {
        this.ruleForm.schoolId = this.schoolId;
        this.ruleForm.schoolName = this.schoolName;
        this.getSecInfo(this.schoolId);
        this.listSysDictByType();
    },
    methods: {
        changeType(val) {
            //console.log('this.ruleForm.sCardType', this.ruleForm.sCardType);
            if (this.ruleForm.sCardType == '3') {
                if (this.schoolId !== '' && this.ruleForm.sClass !== '' && this.ruleForm.userId !== '') {
                // this.$refs['ruleForm'].validate('cardNum');
                // fUserId,
                    getVirtualCard(this.schoolId, this.ruleForm.userId, '0').then(res => {
                        this.ruleForm.verNum = res.data.content;
                    })
                }
            }
        },
        // changeArea(val) {
        //     // if (this.autoFill) return;
        //     this.listSchoolByArea(val);
        // },
    
        // listSchoolByArea(area) {
        //     //console.log('area', area);
        //     if (area === '') {
        //         return false;
        //     } else {
        //         this.schoolList = [];

        //         this.ruleForm.schoolName = '';
        //         this.ruleForm.schoolId = '';
        //         this.gradeList = [];
        //         this.classList = [];
        //         this.ruleForm.sGrade = '';
        //         this.ruleForm.sClass = '';
        //         this.ruleForm.sStudentName = '';
        //         listSchoolByArea(this.ruleForm.provinceId, this.ruleForm.cityId, area).then(res => {
        //             this.schoolList = res.data.content;
        //             //console.log(res.data.content);
        //         });
        //     }
            
        // },

        // schoolVerify(val) {
        //     if (!val) {
        //         this.gradeList = [];
        //         this.classList = [];
        //         this.ruleForm.sGrade = '';
        //         this.ruleForm.sClass = '';
        //         this.ruleForm.sStudentName = '';
        //     } else {
        //         // this.ruleForm.schoolId = val;

        //         this.getSecInfo(val);
        //         this.ruleForm.schoolId = val;
        //     }
        // },

        // 判断是否普通学校/培训学校
        // judgmentSta(val) {
        //     this.schoolList.forEach(item => {
        //         if (val === item.pId) {
        //             this.schoolType = item.sType;
        //         }
        //     });
        // },

        getSecInfo(val) {
            // 判断用户是否确认选择
            if (val) {
                // this.judgmentSta(val);
                if (this.ruleForm.schoolId != '' && this.ruleForm.schoolId !== val) {
                    // this.ruleForm.schoolId = val;
                    this.gradeList = [];
                    this.classList = [];
                    this.ruleForm.sGrade = '';
                    this.ruleForm.sClass = '';
                    this.ruleForm.sStudentName = '';
                }
                
                // 填充省市区
                // let school = this.schoolList.find(s => {
                //     //console.log('123123', val.schoolId, s.pId);
                //     return s.pId == val.schoolId;
                // });
                // this.ruleForm.provinceId = val.provinceId;
                // this.ruleForm.cityId = val.cityId;
                // this.ruleForm.areaId = val.areaId;
                
            } else {
                // this.schoolList = [];
                this.gradeList = [];
                this.classList = [];
                this.ruleForm.schoolName = '';
                this.ruleForm.sGrade = '';
                this.ruleForm.sClass = '';
            }
            
            // this.autoFill = true;
            // this.$nextTick(() => {
            //     this.autoFill = false;
            // });
            this.getGradeName = '';
            this.newSchoolId = val;
            //console.log('val', val);
            if (val) {
                if (this.schoolType === '0') {
                    getGrade(!val ? null : val).then(response => {
                        this.gradeList = response.data.content;
                    });
                } else {
                    this.queryAllClass('');
                }
            }
        },

        // 年级列表
        queryAllGrade(val) {
            //console.log('val', val);
            // 判断用户是否确认选择
            if (val.schoolId) {
                //console.log('111', this.ruleForm.schoolId, val.schoolId);
                this.judgmentSta(val.schoolId);
                // 填充省市区
                // let school = this.schoolList.find(s => s.schoolId == val.schoolId);
                // this.ruleForm.provinceId = school.provinceId;
                // this.ruleForm.cityId = school.cityId;
                // this.ruleForm.areaId = school.areaId;
            } else {
                // this.schoolList = [];
                this.gradeList = [];
                this.classList = [];
                this.ruleForm.schoolName = '';
                this.ruleForm.sGrade = '';
                this.ruleForm.sClass = '';
            }
            this.autoFill = true;
            this.$nextTick(() => {
                this.autoFill = false;
            });
            this.getGradeName = '';
            this.newSchoolId = val.schoolId;
            if (val.schoolId) {
                getGrade(!val.schoolId ? null : val.schoolId).then(response => {
                    this.gradeList = response.data.content;
                    this.classList = [];
                    this.ruleForm.sClass = '';
                });
            }
        },
        // 班级列表
        queryAllClass(gradeId) {
            this.classList = [];
            this.ruleForm.sClass = '';
            if (this.schoolType === '0' && !gradeId) {
                // 
            } else {
                getClass(
                    !this.newSchoolId ? null : this.newSchoolId,
                    !gradeId ? null : gradeId
                ).then(response => {
                    this.classList = response.data.content;
                });
            } 
        },

        vertifyName(val) {
            //console.log(val);
            this.ruleForm.sStudentName = '';
            this.ruleForm.userId = '';
        },

        queryAllName(val) {
            this.ruleForm.userId = val;
            this.changeType();
        },

        // 关系列表
        listSysDictByType() {
            listSysDictByType().then((res) => {
                this.relationList = res.data.content;
            })
        },
        handleClose() {
            this.$refs.ruleForm.resetFields();
            // this.schoolList = [];
            this.ruleForm.userId = '';
            this.ruleForm.sGrade = '';
            this.ruleForm.sClass = '';
            this.ruleForm.sCardType = '';
            this.ruleForm.cardNum = '';
            this.ruleForm.verNum = '';
            this.ruleForm.sRelationType = '';
            this.ruleForm.sRelation = '';

            this.bindCard.dialogFormVisible = false;
        },
        add(ruleForm) {
            this.$refs[ruleForm].validate(valid => {
                if (!valid) {
                    return false;
                } else {
                    if (this.ruleForm.userId === '' || this.ruleForm.sCardType ==='' || this.ruleForm.schoolName === '') {
                        this.$message('请填写完整的信息');
                        return;
                    }

                    // if (this.ruleForm.schoolId === '') {
                    //     this.$message('请选择学校');
                    //     return;
                    // }
                    
                    // sCardNumber, fUserId, fSchoolId, sCardType, fRelationId, sSchoolName, sType
                    if (this.ruleForm.sRelationType == '1' && this.ruleForm.sRelation == '') {
                        this.$message('请选择关系');
                        return;
                    }

                // this.$message("已经添加成功，请稍等更新~");
                // this.loading = false;
                // this.bindCard.dialogFormVisible = false;
                    // let schoolName = '';
                    // this.schoolList.forEach(item => {
                    //     if (this.ruleForm.schoolId == item.pId) {
                    //         schoolName = item.sName;
                    //     }
                    // });
                    // //console.log('this.ruleForm.schoolName', schoolName);
                    // let userId = '';
                    // this.nameList.forEach(item =>{
                    //     if(this.ruleForm.sStudentName == item.value){
                    //         return userId = item.fStudentId;
                    //     }
                    // });

                    if (this.ruleForm.sRelationType === '0') {
                        this.ruleForm.sRelation = '';
                    }
                    this.ruleForm.cardNum = this.ruleForm.cardNum.replace(/\b(0+)/gi, '');
                    let Num = '';
                    if (this.ruleForm.sCardType == '3') {
                        Num = this.ruleForm.verNum;
                    } else {
                        Num = this.ruleForm.cardNum;
                    }
                    if (Num === '') {
                        this.$message('请填写完整的信息');
                        return;
                    }
                    this.upLoading = true;
                    insertCard(
                        Num,
                        this.ruleForm.userId,
                        this.ruleForm.schoolId,
                        this.ruleForm.sCardType,
                        this.ruleForm.sRelation === ''? '1':this.ruleForm.sRelation,
                        this.ruleForm.schoolName,
                        '0'
                    )
                    .then(data => {
                        this.upLoading = false;
                    // this.bindCard.dialogFormVisible = false;
                    // 给父组件传值
                        this.$message({
                            message: '添加成功！',
                            type: 'success'
                        });
                        this.cancel();
                        this.$emit('bindCardState', true);
                    })
                    .catch(Error => {
                        this.upLoading = false;
                        // this.$message(Error);
                    });
                }
            });
        },

        cancel() {
            this.$refs.ruleForm.resetFields();
            this.ruleForm.userId = '';
            this.ruleForm.sGrade = '';
            this.ruleForm.sClass = '';
            this.ruleForm.sCardType = '';
            this.ruleForm.cardNum = '';
            this.ruleForm.verNum = '';
            this.ruleForm.sRelationType = '';
            this.ruleForm.sRelation = '';
            this.bindCard.dialogFormVisible = false;
        }
    }
};
</script>
<style lang="scss" scoped>
.title {
  display: block;
  text-align: left;
  margin-left: 20px;
  font-size: 14px;
  margin-bottom: 18px;
  color: #333;
  position: relative;
  &::after {
    position: absolute;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: -15px;
    top: 10px;
    content: "";
  }
}
.vertifyTip{
    position: absolute;
    top: -25px;
    padding: 5px 0 5px 100px;
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
}
.tip{
  padding: 5px 0;
  color: #ccc;
  line-height: 18px;
}
footer {
  text-align: center;
}
</style>
